<?php

namespace Biz;

use Aliyun\Core\Config;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
use Aliyun\Api\Sms\Request\V20170525\QuerySendDetailsRequest;

class AliyunSms
{
    private $acsClient;

    function __construct($accessKeyId = null, $accessKeySecret = null)
    {
        $config = C('sdk.aliyunsms');
        Config::load();
        // 短信API产品名
        $product = "Dysmsapi";

        // 短信API产品域名
        $domain = "dysmsapi.aliyuncs.com";

        // 暂时不支持多Region
        $region = "cn-hangzhou";

        $accessKeyId = $accessKeyId ? : $config['access_key_id'];
        $accessKeySecret = $accessKeySecret ? : $config['access_key_secret'];

        // 服务结点
        $endPointName = "cn-hangzhou";
        $profile = DefaultProfile::getProfile('cn-hangzhou', $accessKeyId, $accessKeySecret);
        // 增加服务结点
        DefaultProfile::addEndpoint($endPointName, $region, $product, $domain);
        $this->acsClient = new DefaultAcsClient($profile);
    }

    public function sendMobileCode($phoneNumber, $mobileCode, $templateCode = null, $signName = null)
    {
        $config = C('sdk.aliyunsms');
        $templateCode = $templateCode ?: $config['validate_template_code'];
        $signName = $signName ?: $config['default_sign'];
        $params = [
            'code' => $mobileCode,
//            'product' => C('PROJECT_NAME'),
        ];
        return $this->sendSms($phoneNumber, $templateCode, $signName, $params);
    }

    public function sendSms($phoneNumbers, $templateCode, $signName, $templateParam)
    {
        $request = new SendSmsRequest();

        // 必填，设置雉短信接收号码
        if (is_array($phoneNumbers)) $phoneNumbers = implode(',', $phoneNumbers);
        $request->setPhoneNumbers($phoneNumbers);

        // 必填，设置签名名称
        $request->setSignName($signName);

        // 必填，设置模板CODE
        $request->setTemplateCode($templateCode);

        if($templateParam) {
            $request->setTemplateParam(json_encode($templateParam));
        }
        $acsResponse = $this->acsClient->getAcsResponse($request);
        if ($acsResponse->Message === 'OK') {
            return true;
        } else {
            throw new \Exception($acsResponse->Message);
        }
    }
}
